package com.cf.web.advice;

/**
 * cf-game-ControllerExceptionAdvice
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/4/3 21:04
 */

import com.cf.exception.BizStackException;
import com.cf.web.autoconfigure.WebCommonProperty;
import com.cf.constant.EnumReturnCode;
import com.cf.web.controller.MvcHandlers;
import com.cf.exception.BizException;
import com.cf.util.RequestUtil;
import com.cf.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * cf-game-ControllerExceptionAdvice
 * <p>
 * 统一异常处理
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/3/5 17:01
 */
@Slf4j
@ControllerAdvice
public class ControllerExceptionAdvice {

    @Autowired
    private MvcHandlers mvcHandlers;

    @Autowired
    private WebCommonProperty webCommonProperty;


    /**
     * 设置要捕获的异常，并作出处理
     * 注意：这里可以返回试图，也可以放回JSON，这里就当做一个Controller使用
     *
     * @param request {@link NativeWebRequest}
     * @param ex      {@link Exception}
     * @return {@link Map}
     */
    @ExceptionHandler(value = Exception.class)
    public void processUnauthenticatedException(HttpServletRequest request, HttpServletResponse httpServletResponse, Exception ex) throws IOException, BizStackException {
        log.error("处理【{}】发生异常！", request.getRequestURL(), ex);
        ResponseVo fail = (ex instanceof BizException)
                ? ResponseVo.fail(((BizException) ex).getCode(), null, ex.getMessage())
                : ResponseVo.fail(EnumReturnCode.ERROR.getCode(), null, ex.getMessage());
        if (mvcHandlers.isJsonResponse(request)) {
            RequestUtil.renderJson(httpServletResponse, fail);
        } else {
            httpServletResponse.sendRedirect(webCommonProperty.getErrorPage() + "?msg=" + fail.getMsg() + "&code=" + fail.getCode());
        }
    }
}